package com.invoicerecognition.backend.service.impl.student;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.invoicerecognition.backend.mapper.StudentMapper;
import com.invoicerecognition.backend.model.dto.Student;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import com.invoicerecognition.backend.service.student.GetStudentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class GetStudentInfoServiceImpl implements GetStudentInfoService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Map<String, String> getStudentInfo() {

        Map<String, String> resp = new HashMap<>();

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();
        int userId = user.getId();

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Student student = studentMapper.selectOne(queryWrapper);
        if (student == null) {
            resp.put("error_message", "error");
            return resp;
        }
        else {
            resp.put("error_message", "success");
            resp.put("studentId", student.getStudentId());
            resp.put("name", student.getName());
            resp.put("grade", student.getGrade());
            return resp;
        }
    }
}
